package yt.spider.widget.main;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import yt.spider.R;
import yt.spider.SimpleObserver;
import yt.spider.activity.ReadBookActivity;
import yt.spider.adapter.HomeAdapter;
import yt.spider.adapter.MyItemDecoration;
import yt.spider.bean.BookShelfBean;
import yt.spider.dao.DbHelper;
import yt.spider.events.MessageEvent;
import yt.spider.help.BookshelfHelp;
import yt.spider.manage.BitIntentDataManager;

/**
 * Created by 小呆呆 on 2018/1/19.
 */

public class BookShelfFragment extends Fragment {
    private HomeAdapter mHomeAdaper;
    private RecyclerView mRecyclerView;
    private List<BookShelfBean> mList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRecyclerView = (RecyclerView) inflater.inflate(R.layout.fragment_bookshelf, container, false);
        return mRecyclerView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();

        EventBus.getDefault().register(this);
    }

    private void initData() {       //在item里写入（add）数字
        queryBookShelf(false);
    }

    private void initView() {     //更新界面，刷出list
        mRecyclerView = (RecyclerView) this.getView().findViewById(R.id.bookshelf_view);
        setListView();  //调用设置RecyclerView相关操作
    }

    public void setListView()
    //设置RecyclerView一系列必要操作，写在一个函数里，方便调用
    {
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        //加载入分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), MyItemDecoration.VERTICAL_LIST));
        //设置item增加和删除时的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mHomeAdaper = new HomeAdapter(getActivity());
        setLister();
        mRecyclerView.setAdapter(mHomeAdaper);
    }

    private void setLister() {
        //点击事件
        mHomeAdaper.setOnItemClickListener(new HomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position)
            //短按item实现功能，预思点击跳转到阅读界面
            {
                //从数据库中定位position位置跳转
                DbHelper.getInstance().getmDaoSession().getBookShelfBeanDao().insertOrReplace(mList.get(position));
                Intent intent = new Intent(getContext(), ReadBookActivity.class);
                intent.putExtra("from", 1);
                String key = String.valueOf(System.currentTimeMillis());
                intent.putExtra("data_key", key);
                try {
                    BitIntentDataManager.getInstance().putData(key, mList.get(position).clone());
                } catch (CloneNotSupportedException e) {
                    BitIntentDataManager.getInstance().putData(key, mList.get(position));
                    e.printStackTrace();
                }
                startActivity(intent);
            }
           /* {
                Toast.makeText(getActivity(), "点击第" + (position + 1) + "条", Toast.LENGTH_SHORT).show();
                //跳转到阅读界面
                Intent mIntent = new Intent(getActivity(), ReadingActivity.class);
                startActivity(mIntent);
            }*/

            @Override

            public void onItemLongClick(View view, final int position)
            //长按item实现功能，预思实现长按跳出操作书籍相关操作
            {
                new AlertDialog.Builder(getActivity())
                        .setTitle("确认删除吗？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                BookShelfBean bean =  mList.get(position);
                                DbHelper.getInstance().getmDaoSession().delete(bean);
                                mHomeAdaper.removeData(position); //position定位删除item的位置
                            }
                        })
                        .show();
            }
        });
    }

    public void queryBookShelf(final Boolean needRefresh) {
        if (needRefresh) {
        }
        //观察者创立
        Observable.create((ObservableOnSubscribe<List<BookShelfBean>>) e -> {
            List<BookShelfBean> bookShelfList = BookshelfHelp.getAllBook();
            e.onNext(bookShelfList == null ? new ArrayList<>() : bookShelfList);
            e.onComplete();
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SimpleObserver<List<BookShelfBean>>() {
                    @Override
                    public void onNext(List<BookShelfBean> value) {
                        if (null != value) {
                            mList = value;
                            mHomeAdaper.replaceAll(value, "0");
                            if (needRefresh) {
                                //startRefreshBook(value);
                            } else {
                                // mView.refreshFinish();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        //mView.refreshError(NetworkUtil.getErrorTip(NetworkUtil.ERROR_CODE_ANALY));
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /* Do something */
        queryBookShelf(false);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
